package com.link.gateway.core.filter.threadpool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadPoolForInterfaceLogFilter 接口日志线程池
 *
 * @author 欧阳振强
 * @date 2020/04/27
 */
public class ThreadPoolForInterfaceLogFilter {
    private static volatile ThreadPoolExecutor instance;
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 50;
    /**
     * 最大线程数
     */
    private static final int MAXIMUM_POOL_SIZE = 500;
    /**
     * 最大工作队列数
     */
    private static final int MAX_WORK_QUEUE_NUM = 2000;
    /**
     * 闲置线程存活时间
     */
    private static final int KEEP_ALIVE_TIME = 30;

    /**
     * 线程的创建工厂
     */
    private static ThreadFactory threadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable runnable) {
            return new Thread(runnable, "interfaceLogTask#" + mCount.getAndIncrement());
        }
    };

    public static ThreadPoolExecutor getInstance() {
        if (null == instance) {
            synchronized (ThreadPoolForInterfaceLogFilter.class) {
                if (null == instance) {
                    instance = new ThreadPoolExecutor(
                            CORE_POOL_SIZE,
                            MAXIMUM_POOL_SIZE,
                            KEEP_ALIVE_TIME,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(MAX_WORK_QUEUE_NUM),
                            threadFactory
                    );
                    // 允许核心线程接受存活时间的控制
                    instance.allowCoreThreadTimeOut(true);
                }
            }
        }
        return instance;
    }
}
